package com.anbinh.doctor.fragment.account;

import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.LayoutParams;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.anbinh.doctor.R;
import com.anbinh.doctor.adapter.AddressExamAdapter;
import com.anbinh.doctor.fragment.FragmentMain;
import com.anbinh.doctor.model.Address;
import com.anbinh.doctor.model.Address.Data.Item;
import com.anbinh.doctor.model.DataResponse;
import com.anbinh.doctor.model.UserLogin;
import com.anbinh.doctor.request.controller.ServerController;
import com.anbinh.doctor.service.request.OnRequest;
import com.anbinh.doctor.utils.IRcallBak;
import com.anbinh.doctor.utils.Utils;
import com.lsjwzh.widget.materialloadingprogressbar.CircleProgressBar;
import com.mobeta.android.dslv.DragSortListView;

public class FragmentListLocation extends Fragment {
	private static FragmentListLocation fragment = null;
	private View mView;
	private CircleProgressBar loadding;
	private DragSortListView mListview;
	private String token;
	public Item currentLocation;
	private UserLogin userLogin;
	private AddressExamAdapter adapter = null;
	private List<Item> mList;
	int is_default = 0;
	private View fotter;
	private int currentPage = 0;

	public static FragmentListLocation newInstance() {
		if (fragment == null) {
			fragment = new FragmentListLocation();
		}
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		userLogin = Utils.getAccountModel(getActivity(), Utils.KEY_USER);
	}

	private DragSortListView.DropListener onDrop = new DragSortListView.DropListener() {
		@Override
		public void drop(int from, int to) {
			Log.d("drop", from + "-" + to);
			Item item = adapter.getItem(from);

			adapter.notifyDataSetChanged();
			adapter.remove(item);
			adapter.insert(item, to);
			onUpdowLocation(item, from, to);

		}
	};

	private DragSortListView.DragScrollProfile ssProfile = new DragSortListView.DragScrollProfile() {
		@Override
		public float getSpeed(float w, long t) {
			if (w > 0.8f) {
				// Traverse all views in a millisecond
				return ((float) adapter.getCount()) / 0.001f;
			} else {
				return 10.0f * w;
			}
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		currentPage = 0;
		adapter = null;
		mView = inflater.inflate(R.layout.fragment_location, null);
		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mListview = (DragSortListView) mView.findViewById(R.id.listDrag);
		fotter = getActivity().getLayoutInflater().inflate(
				R.layout.footer_loadmore, null);
		fotter.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onLoadData();
			}
		});

		mListview.setDropListener(onDrop);
		mListview.setDragScrollProfile(ssProfile);
		loadding = (CircleProgressBar) mView.findViewById(R.id.loadding);

		mListview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				currentLocation = adapter.getItem(position);
				Bundle bundle = new Bundle();
				bundle.putInt(Utils.KEY, R.id.form_them_diem_kham);
				bundle.putBoolean(Utils.CUSTOMBAR, true);
				bundle.putString(Utils.TITLE, currentLocation.getClinic_name());
				bundle.putInt(Utils.REQUEST_CODE, Utils.UPDATE_LOCATION);
				Utils.getNewIntent((Activity) getActivity(), bundle);
			}

		});

		onLoadData();

	}

	public void showPopupMenu(final Item item, final int location) {
		final Dialog dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.getWindow().setBackgroundDrawableResource(
				R.drawable.abs__menu_dropdown_panel_holo_light);
		dialog.setCanceledOnTouchOutside(true);
		DisplayMetrics metrics = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay()
				.getMetrics(metrics);

		int width = metrics.widthPixels;

		dialog.setContentView(R.layout.dialog_menu_location);
		dialog.getWindow().setLayout(width - 60, LayoutParams.WRAP_CONTENT);

		TextView lblSetDefault = (TextView) dialog
				.findViewById(R.id.lblSetDefault);
		if (item.getIs_default() == 1)
			lblSetDefault.setVisibility(View.GONE);

		lblSetDefault.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onSetDefault(item, location);
				dialog.dismiss();
			}
		});

		TextView lblXoaDc = (TextView) dialog.findViewById(R.id.lblXoaDc);
		lblXoaDc.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onDeleteLocation(item);
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	protected void onUpdowLocation(final Item item,
			final int startPriorityOrder, final int endPriorityOrder) {

		ServerController.getInstance(getActivity()).requestendPriorityOrder(
				userLogin.getData().getToken(), startPriorityOrder,
				endPriorityOrder, new OnRequest<DataResponse>() {

					@Override
					public void onSuccess(DataResponse data) {
						FragmentMain.newInstance().setRefreshAppointMent(true);
						if (getActivity() == null)
							return;
						Utils.showMessage(getActivity(), data.getDescription());
						// onResetData();
						// onLoadData();
					}

					@Override
					public void onError(int errorCode, String message) {
						loadding.setVisibility(View.INVISIBLE);
						Utils.disableEnableControls(true, mView);

					}
				});
	}

	protected void onDeleteLocation(final Item item) {
		Utils.onLoadding(mView, true);
		ServerController.getInstance(getActivity()).reuquestAddressRemove(
				userLogin.getData().getToken(), item.getId(),
				item.getIs_active(), new OnRequest<DataResponse>() {
					@Override
					public void onSuccess(DataResponse data) {
						if (getActivity() == null)
							return;
						Utils.onLoadding(mView, false);
						FragmentMain.newInstance().setRefreshAppointMent(true);
						Utils.showMessage((Activity) getActivity(),
								data.getDescription());
						mList.remove(item);
						adapter.notifyDataSetChanged();
					}

					@Override
					public void onError(int errorCode, String message) {
						Utils.onLoadding(mView, false);
					}
				});

	}

	protected void onSetDefault(Item item, final int location) {

		loadding.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);

		ServerController.getInstance(getActivity()).reuquestAddressUpdate(
				userLogin.getData().getToken(), item.getId(),
				item.getClinic_name(), item.getAddress(), 1, 1,
				item.getPhone(), item.getMap_position(),
				new OnRequest<DataResponse>() {

					@Override
					public void onSuccess(DataResponse data) {
						FragmentMain.newInstance().setRefreshAppointMent(true);
						Utils.showMessage((Activity) getActivity(),
								data.getDescription());
						onResetData();
						onLoadData();
					}

					@Override
					public void onError(int errorCode, String message) {
						loadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);

					}
				});
	}

	public void onResetData() {
		adapter = null;
		currentPage = 0;
	}

	public void onLoadData() {
		Utils.onLoadding(mView, true);
		token = userLogin.getData().getToken();
		ServerController.getInstance(getActivity()).reuquestListAddress(token,
				currentPage, new OnRequest<Address>() {

					@Override
					public void onSuccess(Address data) {
						Utils.onLoadding(mView, false);
						if (getActivity() == null)
							return;

						if (data.getResponsecode() >= 0
								&& data.getData() != null
								&& data.getData().getAddress() != null
								&& data.getData().getAddress().size() > 0) {
							currentPage = data.getData().getPaging()
									.getCurrentPage();
							int lastPage = data.getData().getPaging()
									.getLastPage();

							if (currentPage < lastPage) {
								mListview.addFooterView(fotter);
							} else if (mListview.getFooterViewsCount() > 0) {
								mListview.removeFooterView(fotter);
							}
							if (adapter == null) {
								mList = data.getData().getAddress();
								adapter = new AddressExamAdapter(getActivity(),
										R.layout.item_diadiemkham, mList, 1,
										new IRcallBak() {

											@Override
											public void onDisplay(int type,
													Bundle data) {
												showPopupMenu(mList.get(type),
														type);
											}
										});
								mListview.setAdapter(adapter);
							} else {
								mList.addAll(data.getData().getAddress());
								adapter.notifyDataSetChanged();
							}

						} else {
							Utils.showMessage(getActivity(),
									data.getDescription());
						}
					}

					@Override
					public void onError(int errorCode, String message) {
						Utils.onLoadding(mView, false);
					}
				});
	}

	public Item getCurrentLocation() {
		return currentLocation;
	}

	public void showEdit(boolean isShow) {
		if (mList == null || mList.size() == 0)
			return;

		for (int i = 0; i < mList.size(); i++) {
			mList.get(i).setEdit(isShow);
		}
		adapter.notifyDataSetChanged();
	}

}
